(function() {
	var app = angular.module('warningNoticeApp', [ 'ui.bootstrap' ]);
	app
			.controller(
					'warningNoticeController',
					function($uibModal, $scope, $http, $filter, $log) {
						var basePath = $scope.getAppBasePath();
						var controller = this;
						$scope.viewComponent = {};

						// 搜索条件定义
						this.queryCondition = {
							"monitoringState" : "",
							"monitoringIndex" : "",
							"idexKpi" : "",
							"earlyWarningLevel" : "",
							"startTime" : "",
							"endTime" : "",
							"page" : "1",
							"size" : "300"

						};

						// 分页信息定义
						this.paginationInfo = {
							"maxSize" : 5,
							"totalPages" : 0,
							"totalElements" : 0
						};

						// 跳转页数，回车事件
						$scope.clickEvent = function() {
							controller.queryCondition.page = controller.queryCondition.forwordPage;
							search();
						}
						$scope.enterEvent = function(e) {
							var keycode = window.event ? e.keyCode : e.which;
							if (keycode == 13) {
								$scope.clickEvent();
							}
						}
						// 分页，翻页事件
						this.pageChanged = function() {
							search();
						}

						controller.queryCondition.date = new Date();
						controller.queryCondition.date2 = new Date();
						controller.format = "yyyy-MM-dd 00:00:00";
						controller.format2 = "yyyy-MM-dd 23:59:59";
						controller.altInputFormats = [ 'yyyy-MM-dd HH:mm:ss' ];

						controller.popup1 = {
							opened : false
						};
						controller.popup2 = {
							opened : false
						};

						controller.open1 = function() {
							controller.popup1.opened = true;
						};
						controller.open2 = function() {
							controller.popup2.opened = true;
						};
						/*
						 * controller.dateOptions = { customClass :
						 * getDayClass,// 自定义类名 dateDisabled : isDisabled //
						 * 是否禁用 }
						 */
						var tomorrow = new Date();
						tomorrow.setDate(tomorrow.getDate() + 1);
						var afterTomorrow = new Date();
						afterTomorrow.setDate(tomorrow.getDate() + 1);
						$scope.events = [ {
							date : tomorrow,
							status : 'full'
						}, {
							date : afterTomorrow,
							status : 'partially'
						} ];

						// 为日期面板中的每个日期（默认42个）返回类名。传入参数为{date: obj1, mode: obj2}
						function getDayClass(obj) {
							var date = obj.date, mode = obj.mode;
							if (mode === 'day') {
								var dayToCheck = new Date(date).setHours(0, 0,
										0, 0);

								for (var i = 0; i < $scope.events.length; i++) {
									var currentDay = new Date(
											$scope.events[i].date).setHours(0,
											0, 0, 0);

									if (dayToCheck === currentDay) {
										return $scope.events[i].status;
									}
								}
							}
							return '';
						}
						// 设置日期面板中的所有周六和周日不可选
						function isDisabled(obj) {
							var date = obj.date, mode = obj.mode;
							return mode === 'day'
									&& (date.getDay() === 0 || date.getDay() === 6);
						}

						function getDayClass(data) {
							var date = data.date, mode = data.mode;
							if (mode === 'day') {
								var dayToCheck = new Date(date).setHours(0, 0,
										0, 0);

								for (var i = 0; i < $scope.events.length; i++) {
									var currentDay = new Date(
											$scope.events[i].date).setHours(0,
											0, 0, 0);

									if (dayToCheck === currentDay) {
										return $scope.events[i].status;
									}
								}
							}

							return '';
						}

						// 事件控件改变时间事件
						this.changeDate = function() {
							controller.queryCondition.startTime = $filter(
									'date')(controller.queryCondition.date,
									'yyyy-MM-dd 00:00:00');
							controller.queryCondition.endTime = $filter('date')
									(controller.queryCondition.date2,
											'yyyy-MM-dd 23:59:59');
						}

						// 检索部分下拉框取值
						$.ajax({
									type : "post",
									url : basePath+ "/get/getSelectOptionValue",
									dataType : "json",
									contentType : "application/json",
									success : function(data) {
										var resultJson = angular.fromJson(data);
										$scope.monitorStatus = resultJson.monitorStatus;
										$scope.monitorIndex = resultJson.monitorIndex;
										$scope.EarlyWarningLevel = resultJson.earlyWarnLevel;
										// 手动刷新
										$scope.$apply();
									}
								});

		

						// 指标KPI选择框数据获取
						$scope.kpiIndex = [ {
							name : "cpu-use"
						}, {
							name : "network-packet_loss"
						}, {
							name : "mem-cache_kb"
						} ];


						// 详细信息查看(弹出层展示)
						this.viewWarnNoticeInfo = function(data) {
							$scope.waringNoticeDetails = angular.copy(data)
									|| {};
							var modalInstanceUpdate = $uibModal
									.open({
										backdrop : 'static',
										keyboard : false,
										scope : $scope,
										// animation :
										// $scope.animationsEnabled,// 打开时的动画开关
										templateUrl : 'js/controller/warningNotice/viewWarnNotice.html',// 模态框的页面内容,这里的url是可以自己定义的,也就意味着什么都可以写
										controller : 'viewWarnNoticeController',// 这是模态框的控制器,是用来控制模态框的
										ariaLabelledBy : 'modal-title',
										ariaDescribedBy : 'modal-body',
									// size : "lg",// 模态框的大小尺寸
									});
						}

						// 初始化方法
						this.init = function() {

							search();
						}
						/**
						 * 初始化数据
						 */
						this.init();

						// 搜索按钮事件
						this.search = function() {
							search();
						}

						// 重置按钮事件
						this.reset = function() {
							$scope.selectedMonitorState = ""
							$scope.selectedMonitorIndex = "";
							$scope.selectedKpiIndex = "";
							$scope.selectedEarlyWarningLevel = "";
							$scope.controller.queryCondition.date = new Date();
							$scope.controller.queryCondition.date2 = new Date();
						}
						function search() {
							// 获取页面搜搜寻参数
							controller.queryCondition.monitoringStatus = $scope.selectedMonitorState
									|| "";
							controller.queryCondition.monitoringIndex = $scope.selectedMonitorIndex
									|| "";
							controller.queryCondition.idexKpi = $scope.selectedKpiIndex
									|| "";
							controller.queryCondition.earlyWarningLevel = $scope.selectedEarlyWarningLevel
									|| "";
							$.ajax({
										type : "post",
										url : basePath
												+ "/get/getWarnNtticeInfo",
										dataType : "json",
										contentType : "application/json",
										data : JSON
												.stringify(controller.queryCondition),
										success : function(data) {
											var resultJson = angular
													.fromJson(data);
											controller.dataList = resultJson.data;
											controller.paginationInfo.totalPages = resultJson.totalPages;
											controller.paginationInfo.totalElements = resultJson.totalElements;
											var appendHtml="";
											for(var i=0 ; i<controller.dataList.length;i++){
												var strDiv='<div class="warnLevel"></div>';
												switch(controller.dataList[i].warnLevel)
												{
												case "预警":
													strDiv='<div class="warnLevel earlyWarn"></div>';
													break;
												case "危险":
													strDiv='<div class="warnLevel danger"></div>';
													break;
												case "严重":
													strDiv='<div class="warnLevel serious"></div>';
													  break;
												default:
													strDiv='<div class="warnLevel"></div>';
												};
												appendHtml=appendHtml
													+'<tr>'
													+'<td>'
												+'<div class="showIcon active"></div>'
											+'</td>'
											+'<td class="midTableTd" style="text-align: left;">'+strDiv+controller.dataList[i].kpiName+'</td>'
											+'<td class="midTableTd">'+controller.dataList[i].monitorStatus+'</td>'
											+'<td class="midTableTd">'+controller.dataList[i].alarmDate+'</td>'
											+'<td class="midTableTd">'+controller.dataList[i].warnLevel+'</td>'
											+'<td class="midTableTd">'+controller.dataList[i].describes+'</td>'
											+'<td class="midTableTd">'+controller.dataList[i].ip+'</td>'
											+'<td><div class="option"><div class="optionList">'
														+'<div class="optionItem active" value=1>主机曲线'
															+'<div class="optionItemSelect"></div>'
														+'</div>'
														+'<div class="optionItem" value=6>应用关联'
														+'<div class="optionItemSelect"></div>'
														+'</div>'
														+'<div class="optionItem" value=7>调用链'
														+'<div class="optionItemSelect"></div>'
														+'</div>'
														+'<div class="optionItem" value=4>拓扑'
														+'<div class="optionItemSelect"></div>'
													+'</div>'
												+'</div>'
											+'</div>'
										+'</td>'
									+'</tr>'
									+'<tr class="warnContent">'
									+'<td colspan="8">'
									+'<table border="0" cellspacing="0" cellpadding="0" class="warnContentTable">'
									+'<tr>'
										+'<th>触发告警指标</th>'
										+'<th>类型</th>'
										+'<th>HOST</th>'
										+'<th>告警联系人</th>'
										+'<th>严重联系人</th>'
										+'<th>危险联系人</th>'
										+'<th>是否解决</th>'
										+'<th>描述</th>'
										+'</tr>'
									+'<tr>'
									+'<td>'+controller.dataList[i].kpiNametriggerWarnIndex+'</td>'
									+'<td>'+controller.dataList[i].type+'</td>'
									+'<td>'+controller.dataList[i].hostName+'</td>'
									+'<td>'+controller.dataList[i].warnContact+'</td>'
									+'<td>'+controller.dataList[i].seriousContact+'</td>'
									+'<td>'+controller.dataList[i].dangerContact+'</td>'
									+'<td>'+controller.dataList[i].isResolved+'</td>'
									+'<td>'+controller.dataList[i].describes+'</td>'
									+'</tr>'
									+'</table>'
									+'<div class="warnContentButton">'
									+'<button class="logRetrievalBtn optionItem" value=3>日志检索</button>'
									+'<button class="alarmConfigurationBtn optionItem" value=2>告警配置</button>'
									+'<button class="webShellBtn optionItem" value=5>WEB SHELL</button>'
									+'</div>'
									+'</td>'
									+'</tr>';
												
											}//for 模板构建完毕
											$("#warningNoticeTable").append(appendHtml);
											
											// 手动刷新
											$scope.$apply();
											bangding();
										}
									});
						}
						//页面点击事件动态效果统一绑定
						function bangding(){
							$(".topDivItem").click(function() {
								$(this).addClass("active").siblings().removeClass('active')
							})
							$(".midDivMain").click(function() {
								$(this).parent().find(".Dropmenu").toggle()
								$(this).parent().parent().siblings().find(".Dropmenu").hide()
							})
							$('.pending').click(function() {
								$('.pendingDiv').show();
								$('.resolvedDiv').hide();
							})

							$('.DropmenuItem').on('click', function() {
								$(this).addClass("active").siblings().removeClass("active").parent().hide().parent().parent().find(".midDivMain").text($(this).text())
							})
							$(".midDivItem").click(function() {
								$(this).addClass("active").siblings().removeClass("active")
							})
							$(".option").click(function() {
								$(this).find(".optionList").toggle()
								$(this).parent().parent().siblings().find(".optionList").hide()
							})
							$('.optionItem').on('click', function() {
								$(this).addClass('active').siblings().removeClass('active')
								popupIframe($(this)[0].value);
							})
							$(".midTableTd").on('click',function(){
								$(this).parent().next().toggleClass('active')
								$(this).parent().find(".showIcon").toggleClass('active')
							})
							$(".midTable tr .showIcon").on('click',function(){
								$(this).toggleClass('active')
								$(this).parent().parent().next().toggleClass('active')
							})
						}
						/*
						 * 日质检索
						 * 
						 */
						this.logSearch=function(){
							var viewWarnSearchLog = $uibModal
							.open({
								backdrop : 'static',
								keyboard : false,
								scope : $scope,
								// animation :
								// $scope.animationsEnabled,// 打开时的动画开关
								templateUrl : 'js/controller/warningNoticeRelease/warningIfram.html',// 模态框的页面内容,这里的url是可以自己定义的,也就意味着什么都可以写
								controller : 'viewWarnSearchLogController',// 这是模态框的控制器,是用来控制模态框的
								ariaLabelledBy : 'modal-title',
								ariaDescribedBy : 'modal-body',
							    size : "lg",// 模态框的大小尺寸
							});
							
						}


						//公共弹窗方法
						function popupIframe(data) {
							var htmlMap=new Map();
							htmlMap.set(1, {src:"js/controller/warningNoticeRelease/popupIframe.html",size:"iframclass1"});
							htmlMap.set(2, {src:"js/controller/warningNoticeRelease/popupIframe.html",size:"iframclass1"});
							htmlMap.set(3, {src:"js/controller/warningNoticeRelease/popupIframe.html",size:"iframclass1"});
							htmlMap.set(4, {src:"js/controller/warningNoticeRelease/popupIframe.html",size:"iframclass1"});
							htmlMap.set(5, {src:"js/controller/warningNoticeRelease/popupIframe.html",size:"iframclass1"});
							htmlMap.set(6, {src:"js/controller/warningNoticeRelease/popupIframe.html",size:"iframclass1"});
							htmlMap.set(7, {src:"js/controller/warningNoticeRelease/popupIframe.html",size:"iframclass1"});
                            /*
                            	1  主机曲线
								2  告警配置
								3  日志检索
								4  拓扑
								5 webshell
								6  应用关联
								7  调用链 
							*/
							var modalInstance = $uibModal.open({
										backdrop : 'static',//控制背景，允许的值：true（默认），false（无背景），“static” - 背景是存在的，但点击模态窗口之外时，模态窗口不关闭
										keyboard : true,   //当按下Esc时，模态对话框是否关闭，默认为ture
										scope : $scope,    //一个作用域为模态的内容使用
										templateUrl :htmlMap.get(parseInt(data)).src ,// 模态框的页面内容,这里的url是可以自己定义的,也就意味着什么都可以写
										resolve: { items: parseInt(data)},//定义一个成员并将他传递给$modal指定的控制器
										controller : 'popupIframeController',// 这是模态框的控制器,是用来控制模态框的
										size : 'iframclass1',   // 模态框的大小尺寸 $uibModal.open 有三种默认可选size:'lg''md''sm'  也可以自定义class
							});
						}	
						
						/**
						 * 时间格式Format方法
						 */
						Date.prototype.Format = function(fmt) { // author: meizz
							var o = {
								"M+" : this.getMonth() + 1, // 月份
								"d+" : this.getDate(), // 日
								"H+" : this.getHours(), // 小时
								"m+" : this.getMinutes(), // 分
								"s+" : this.getSeconds(), // 秒
								"q+" : Math.floor((this.getMonth() + 3) / 3), // 季度
								"S" : this.getMilliseconds()
							// 毫秒
							};
							if (/(y+)/.test(fmt))
								fmt = fmt.replace(RegExp.$1, (this
										.getFullYear() + "")
										.substr(4 - RegExp.$1.length));
							for ( var k in o)
								if (new RegExp("(" + k + ")").test(fmt))
									fmt = fmt
											.replace(
													RegExp.$1,
													(RegExp.$1.length == 1) ? (o[k])
															: (("00" + o[k])
																	.substr(("" + o[k]).length)));
							return fmt;
						}

					})
					.controller('viewWarnNoticeController',
					function($scope, $uibModalInstance, $http, $log) {
						$scope.load = function() {
							$scope.waringNoticeDetails;
						}
						$scope.cancel = function() {
							// dismiss也是在模态框关闭的时候进行调用,而它返回的是一个reason
							$uibModalInstance.dismiss('cancel');
						};
					})
					
	.controller('popupIframeController',
			function($scope, $uibModalInstance) {
			/*
    			1  主机曲线
				2  告警配置
				3  日志检索
				4  拓扑
				5 webshell
				6  应用关联
				7  调用链 
			 */
				$scope.load = function() {
					switch($scope.$resolve.items)
					{
					case 1:
						$("#popupIframeTitle").html("主机曲线");
						$('#iframeId').attr('src', $scope.getAppBasePath()+"/get/getWebShell");
						break;
					case 2:
						$("#popupIframeTitle").html("告警配置");
						$('#iframeId').attr('src', $scope.getAppBasePath()+"/index");
						break;
					case 3:
						$("#popupIframeTitle").html("日志检索");
						$('#iframeId').attr('src', "http://10.145.196.83:8084/logv1/index?platform=msc&startTime=2018-05-18&endTime=2018-07-10 12:12:12&searchIndex=&selctedLogType=all,error,error,mid,error,mid,counter,timer,gauge");
						  break;
					case 4:
						$("#popupIframeTitle").html("拓扑");
						$('#iframeId').attr('src', $scope.getAppBasePath()+"/get/getWebShell");
						break;
					case 5:
						$("#popupIframeTitle").html("webshell");
						$('#iframeId').attr('src', $scope.getAppBasePath()+"/get/getWebShell");
						break;
					case 6:
						$("#popupIframeTitle").html("应用关联");
						$('#iframeId').attr('src', $scope.getAppBasePath()+"/get/getWebShell");
						  break;
					case 7:
						$("#popupIframeTitle").html(" 调用链");
						$('#iframeId').attr('src', $scope.getAppBasePath()+"/get/getWebShell");
						  break;
					default:
						$("#popupIframeTitle").html("webshell");
						$('#iframeId').attr('src', $scope.getAppBasePath()+"/get/getWebShell");
					};
				}
				$scope.cancel = function() {
					// dismiss也是在模态框关闭的时候进行调用,而它返回的是一个reason
					$uibModalInstance.dismiss('cancel');
				};
			})

})();
